﻿using MxWeiXinPF.API.Payment.wxpay;
using MxWeiXinPF.Common;
using MxWeiXinPF.Web.admin.sms;
using MxWeiXinPF.WeiXinComm;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.CommonAPIs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace MxWeiXinPF.Web.api.payment.wxpay
{
    public partial class payResult : System.Web.UI.Page
    {
        protected Model.orders ordertmp = new Model.orders();
        protected string openid = "";
        protected int otid = 0;
        protected string fahuoInfo = "";
        protected string token = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                return;
                openid = MyCommFun.RequestOpenid();
                otid = MyCommFun.RequestInt("otid");
                int wid = MyCommFun.RequestWid();

                if (openid == "" || otid == 0 || wid == 0)
                {
                    LogHelper.WriteLog(typeof(payResult), otid.ToString() + "wid" + wid.ToString() + "openid=" + openid);
                    return;
                }
                lock (this)
                {
                    try
                    {
                        object idx = CacheHelper.Get("tid");
                        if (idx == null)
                        {
                            HashSet<int> ids = new HashSet<int>();
                            ids.Add(otid);
                            CacheHelper.Insert("tid", ids);
                        }
                        else
                        {
                            HashSet<int> ids = idx as HashSet<int>;
                            if (ids != null && ids.Contains(otid))
                            {
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(typeof(payResult), ex);
                    }
                }

                try
                {
                    WeiXinCRMComm wxComm = new WeiXinCRMComm();
                    string err = "";
                   // token = wxComm.getAccessToken(39, out err);

                    BLL.orders otBll = new BLL.orders();
                    ordertmp = otBll.GetModel(otid, wid);
                    if (ordertmp != null && ordertmp.payment_status != 2)
                    {
                        ordertmp.payment_status = 2;
                        ordertmp.status = 2;
                        if (otBll.Update(ordertmp))
                        {
                            LogHelper.WriteLog(typeof(payResult), "订单状态修改成功,订单编号:" + ordertmp.id);

                            TransferToShopMgr(ordertmp);
                            SendMsg(ordertmp);
                        }
                        else {
                            LogHelper.WriteLog(typeof(payResult), "订单状态修改失败,订单编号:" + ordertmp.id);
                        }

                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(payResult), ex);
                }

            }
        }

        private void TransferToShopMgr(Model.orders morder)
        {
            try
            {
                if (morder.shopid == 39)
                {
                    LogHelper.WriteLog(typeof(payResult), "易药宝的订单,无需转账");
                    return;
                }
                if (morder.transfer_fee < 1)
                {
                    LogHelper.WriteLog(typeof(payResult), "小于1元的订单,无需转账");
                    return;
                }
                BLL.dt_transfer otTran = new BLL.dt_transfer();
                Model.dt_transfer mdt = new Model.dt_transfer();
                mdt.create_time = DateTime.Now;
                mdt.status = 0;
                mdt.orderid = morder.id;
                mdt.shopid = morder.shopid;
                mdt.wid = morder.wid;
                mdt.pay_time = DateTime.Now;
                int id = otTran.Add(mdt);
                if (id <= 0)
                {
                     
                    //添加记录失败,记录日志
                    LogHelper.WriteLog(typeof(payResult), string.Concat("添加转账记录失败,订单ID=", id));
                }
                LogHelper.WriteLog(typeof(payResult), string.Concat("添加转账记录成功,订单ID=", id));
               // Transfer(mdt, morder);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(payResult), ex);
            }

 
        }

        private void SendMsg(Model.orders morder)
        {
            try
            {
                Model.users umodel = new BLL.wx_dt_user_BaseData().GetModelByOpenID(morder.openid);
                Model.manager mman = new BLL.manager().GetModel(morder.shopid);
                if (mman != null)
                {

                    if (!string.IsNullOrEmpty(mman.shopclerkid))
                    {
                        //如果指定了微信店长,则发送模板消息
                        if (!SendTemplateMsg("", morder, umodel, mman))
                        {//发送模版消息失败
                            SendSMMsg("", morder, umodel, mman);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(mman.telephone))
                        {
                            SendSMMsg("", morder, umodel, mman);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(payResult), ex);
            }

        }


        private bool SendTemplateMsg(string content, MxWeiXinPF.Model.orders model, Model.users umodel, Model.manager mmodel)
        {
            if (mmodel == null)
            {
                return false;
            }

            content = string.Concat("你好,你的店铺:", mmodel.real_name, "的客户:", umodel.nick_name, "有一张订单付款成功了,请尽快安排发货");
            Model.wx_userweixin weixin = new MxWeiXinPF.BLL.wx_userweixin().GetModel(mmodel.agentId);
            if (weixin == null)
            {
                return false;
            }
            if (!AccessTokenContainer.CheckRegistered(weixin.AppId))
            {
                AccessTokenContainer.Register(weixin.AppId, weixin.AppSecret);
            }
            if (string.IsNullOrEmpty(mmodel.shopclerkid))
            {
                return false;
            }
            WxJsonResult ret = Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(weixin.AppId, mmodel.shopclerkid, content);
            if (ret.errcode == 0)
            {
                return true;
            }
            return false;
        }

        private bool SendSMMsg(string content, MxWeiXinPF.Model.orders model, Model.users umodel, Model.manager mmodel)
        {
            if (mmodel == null)
            {
                return false;
            }
            BlueSmsMgr sm = new BlueSmsMgr(39);
            content = string.Concat("你好,你的店铺:", mmodel.user_name, "的客户:", umodel.nick_name, "有一张订单付款成功了,请尽快安排发货");
            sm.SendSMS(mmodel.telephone, content);
            return false;
        }

        private bool Transfer(Model.dt_transfer mdt,Model.orders morder)
        {
            if (mdt == null)
            {
                return false;
            }
            BLL.manager bman = new BLL.manager();
            qypay pays = new qypay();
            MxWeiXinPF.BLL.dt_transfer btran = new MxWeiXinPF.BLL.dt_transfer();
            Model.manager mman = bman.GetModel(mdt.shopid);
            try
            {
                if (mman != null && !string.IsNullOrEmpty(mman.shopclerkid))
                {
                    string xml = pays.Transfer("1", morder.real_amount, mman.shopclerkid, mman.real_name);
                    SortedDictionary<string, object> mvals = FromXml(xml);
                    if (mvals == null)
                    {
                        //添加记录失败,记录日志
                        LogHelper.WriteLog(typeof(payResult), string.Concat("添加企业向店铺转账记录失败，返回失败", mvals["return_msg"], mvals["result_code"], mvals["err_code"]));
                    }
                    if (mvals["return_code"].ToString().ToUpper() == "SUCCESS" && mvals["return_code"].ToString().ToUpper() == "SUCCESS" && mvals["return_msg"].ToString() == "") //返回失败
                    {
                        mdt.status = 1;
                        btran.Update(mdt);
                        LogHelper.WriteLog(typeof(payResult), string.Concat("添加企业向店铺转账成功,订单号码为:", mdt.id.ToString()));
                    }
                    else
                    {
                        mdt.status = 0;
                        btran.Update(mdt);
                        //添加记录失败,记录日志
                        LogHelper.WriteLog(typeof(payResult), string.Concat("添加企业向店铺转账记录失败，返回失败", mvals["return_msg"], mvals["result_code"], mvals["err_code"]));
                    }
                }
            }
            catch (Exception ex)
            {
                mdt.status = 0;
                btran.Update(mdt);
                LogHelper.WriteLog(typeof(payResult), string.Concat("添加企业向店铺转账失败,", ex.Message));
            }


            return true;
        }

        public SortedDictionary<string, object> FromXml(string xml)
        {
            SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
            if (string.IsNullOrEmpty(xml))
            {
                return null;
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
            }
            return m_values;
        }
    }
}